package Matrix;

import java.util.ArrayList;
import java.util.List;

/**
 * 73.矩阵置零
 * 给定一个 m x n 的矩阵，如果一个元素为 0 ，则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。
 */
public class setZeroes {

    /**
     * hot100一刷
     */
    public void setZeroes(int[][] matrix) {
        List<int[]> list = new ArrayList<int[]>();
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if (matrix[i][j] == 0) {
                    list.add(new int[]{i, j});
                }
            }
        }
        for (int[] temp : list) {
            int x = temp[0];
            int y = temp[1];
            for (int i = 0; i < matrix.length; i++) {
                matrix[i][y] = 0;
            }
            for (int j = 0; j < matrix[0].length; j++) {
                matrix[x][j] = 0;
            }
        }
    }

    /**
     * hot100二刷
     */
    public void setZeroes2(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        boolean row = false;
        boolean col = false;
        for (int i = 0; i < m; i++) {
            if (matrix[i][0] == 0) col = true;
        }
        for (int i = 0; i < n; i++) {
            if (matrix[0][i] == 0) row = true;
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (matrix[0][j] == 0 || matrix[i][0] == 0) {
                    matrix[i][j] = 0;
                }
            }
        }
        if (col) {
            for (int i = 0; i < m; i++) {
                matrix[i][0] = 0;
            }
        }
        if (row) {
            for (int i = 0; i < n; i++) {
                matrix[0][i] = 0;
            }
        }
    }
}
